import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../providers/todos_provider.dart';
import '../../utils/keyboard_utils.dart';

/// 待办事项页面（Riverpod状态管理）
class TodosPage extends ConsumerStatefulWidget {
  const TodosPage({super.key});

  @override
  ConsumerState<TodosPage> createState() => _TodosPageState();
}

class _TodosPageState extends ConsumerState<TodosPage> {
  final TextEditingController _controller = TextEditingController();

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void _addTodo() {
    if (_controller.text.trim().isNotEmpty) {
      ref.read(todosProvider.notifier).addTodo(_controller.text.trim());
      _controller.clear();
      FocusScope.of(context).unfocus();
    }
  }

  @override
  Widget build(BuildContext context) {
    final todos = ref.watch(filteredTodosProvider);
    final filter = ref.watch(todoFilterProvider);
    final totalTodos = ref.watch(totalTodosProvider);
    final completedTodos = ref.watch(completedTodosProvider);
    final activeTodos = ref.watch(activeTodosProvider);

    return DismissKeyboardScaffold(
      appBar: AppBar(title: const Text('待办事项'), backgroundColor: Theme.of(context).colorScheme.inversePrimary),
      child: Column(
        children: [
          // 统计信息
          Container(
            padding: const EdgeInsets.all(16),
            color: Colors.blue.shade50,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _buildStatItem('总计', totalTodos, Colors.blue),
                _buildStatItem('待完成', activeTodos, Colors.orange),
                _buildStatItem('已完成', completedTodos, Colors.green),
              ],
            ),
          ),

          // 过滤器
          Padding(
            padding: const EdgeInsets.all(8),
            child: SegmentedButton<TodoFilter>(
              segments: const [
                ButtonSegment(value: TodoFilter.all, label: Text('全部'), icon: Icon(Icons.list)),
                ButtonSegment(value: TodoFilter.active, label: Text('待完成'), icon: Icon(Icons.circle_outlined)),
                ButtonSegment(value: TodoFilter.completed, label: Text('已完成'), icon: Icon(Icons.check_circle)),
              ],
              selected: {filter},
              onSelectionChanged: (Set<TodoFilter> newSelection) {
                ref.read(todoFilterProvider.notifier).state = newSelection.first;
              },
            ),
          ),

          // 待办事项列表
          Expanded(
            child: todos.isEmpty
                ? Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.check_circle_outline, size: 64, color: Colors.grey.shade400),
                        const SizedBox(height: 16),
                        Text(
                          filter == TodoFilter.all
                              ? '还没有待办事项'
                              : filter == TodoFilter.active
                              ? '太棒了！没有待完成的事项'
                              : '还没有完成的事项',
                          style: TextStyle(fontSize: 16, color: Colors.grey.shade600),
                        ),
                      ],
                    ),
                  )
                : ListView.builder(
                    itemCount: todos.length,
                    padding: const EdgeInsets.symmetric(horizontal: 8),
                    itemBuilder: (context, index) {
                      final todo = todos[index];
                      return Card(
                        margin: const EdgeInsets.symmetric(vertical: 4),
                        child: ListTile(
                          leading: Checkbox(
                            value: todo.isCompleted,
                            onChanged: (value) {
                              ref.read(todosProvider.notifier).toggleTodo(todo.id);
                            },
                          ),
                          title: Text(
                            todo.title,
                            style: TextStyle(
                              decoration: todo.isCompleted ? TextDecoration.lineThrough : null,
                              color: todo.isCompleted ? Colors.grey : null,
                            ),
                          ),
                          subtitle: Text(_formatDate(todo.createdAt), style: const TextStyle(fontSize: 12)),
                          trailing: IconButton(
                            icon: const Icon(Icons.delete, color: Colors.red),
                            onPressed: () {
                              ref.read(todosProvider.notifier).deleteTodo(todo.id);
                            },
                          ),
                        ),
                      );
                    },
                  ),
          ),

          // 输入框
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.1), blurRadius: 4, offset: const Offset(0, -2))],
            ),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _controller,
                    decoration: const InputDecoration(
                      hintText: '添加新的待办事项...',
                      border: OutlineInputBorder(),
                      contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                    ),
                    onSubmitted: (_) => _addTodo(),
                  ),
                ),
                const SizedBox(width: 8),
                FilledButton.icon(onPressed: _addTodo, icon: const Icon(Icons.add), label: const Text('添加')),
              ],
            ),
          ),
        ],
      ),
      floatingActionButton: completedTodos > 0
          ? FloatingActionButton.extended(
              onPressed: () {
                showDialog(
                  context: context,
                  builder: (context) => AlertDialog(
                    title: const Text('清除已完成'),
                    content: Text('确定要删除所有$completedTodos个已完成的待办事项吗？'),
                    actions: [
                      TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
                      FilledButton(
                        onPressed: () {
                          ref.read(todosProvider.notifier).clearCompleted();
                          Navigator.pop(context);
                        },
                        child: const Text('确定'),
                      ),
                    ],
                  ),
                );
              },
              icon: const Icon(Icons.clear_all),
              label: const Text('清除已完成'),
            )
          : null,
    );
  }

  Widget _buildStatItem(String label, int value, Color color) {
    return Column(
      children: [
        Text(
          value.toString(),
          style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: color),
        ),
        Text(label, style: const TextStyle(fontSize: 12, color: Colors.grey)),
      ],
    );
  }

  String _formatDate(DateTime date) {
    final now = DateTime.now();
    final diff = now.difference(date);

    if (diff.inDays == 0) {
      if (diff.inHours == 0) {
        return '${diff.inMinutes}分钟前';
      }
      return '${diff.inHours}小时前';
    } else if (diff.inDays < 7) {
      return '${diff.inDays}天前';
    } else {
      return '${date.month}月${date.day}日';
    }
  }
}
